package com.ruoyi.web.controller.common;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BaseCommonController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/user/add/{num}/{uuid}")
    public AjaxResult addUser(@RequestBody SysUser sysUser,
                              @PathVariable("num") int num,
                              @PathVariable("uuid") String uuid) {
        String numCache = stringRedisTemplate.opsForValue().get("num:" + uuid);
        if (numCache == null) return AjaxResult.error("验证码超时");
        if (num != Integer.parseInt(numCache)) return AjaxResult.error("验证码错误");
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser.getUserName()))) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(sysUser))) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(sysUser))) {
            return AjaxResult.error("新增用户'" + sysUser.getUserName() + "'失败，邮箱账号已存在");
        }
        sysUser.setCreateBy("用户注册");
        sysUser.setDeptId(108L);
        sysUser.setUserName(sysUser.getPhonenumber());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        synchronized (this) {
            userService.insertUser(sysUser);
        }
        return AjaxResult.success();
    }
}
